<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/5/30
 * Time: 下午1:51
 */

namespace App\Http\Controllers\Api\Diagnose;

use App\Http\Controllers\Controller;

use App\Libs\Pay\WechatPay;
use App\Modules\Diagnose\Services\OrderDiagnoseService;
use App\Modules\Order\Services\OrderService;
use App\Modules\Bill\Services\BillService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Modules\Diagnose\Services\GraphicService;
use TencentCloud\Iot\V20180123\Models\Product;
use Illuminate\Support\Facades\DB;


class PayCallbackController extends Controller
{
    const ORDER_STATUS_UNPAID = 0; //未支付
    const ORDER_STATUS_PAID = 1;   //已支付
    const ORDER_STATUS_FAILED = 2; //支付失败
    const ORDER_STATUS_REFUND = 3; //退款

    const MINI_WECHAT = 'MINI_WECHAT';  //微信小程序
    const WECHAT = 'WECHAT';            //微信支付
    const ALIPAY = 'ALIPAY';            //支付宝支付

    /**
     * 微信小程序支付回调
     *
     * @param Request $request
     */
    public function appletCallback(Request $request) {
        Log::useDailyFiles(storage_path('logs/diagnose_pay/applet.log'));
        //\Log::info($request->all());
        $app = OrderService::getWechatPayInstance()->getInstance();
        $response = $app->handlePaidNotify(function($message, $fail){
            $messageJson = json_encode($message);
            Log::info($messageJson);
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = OrderDiagnoseService::findByTradeNo($message['out_trade_no']);
            $order->notify_data = $messageJson;
            if (!$order || $order->status == self::ORDER_STATUS_PAID) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->pay_end_at = date('Y-m-d H:i:s',time()); // 更新支付时间为当前时间
                    $order->status = self::ORDER_STATUS_PAID;
                    $order->transaction_id = $message['transaction_id'];

                // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = self::ORDER_STATUS_FAILED;
                }else{
                    Log::info('订单号:'.$message['out_trade_no'].'==>'.'订单状态错误');
                    return $fail('订单状态错误');
                }
            } else {
                Log::info('订单号:'.$message['out_trade_no'].'==>'.'通信失败，请稍后再通知我');
                return $fail('通信失败，请稍后再通知我');
            }
            DB::beginTransaction();
            try{
                $orderSave = $order->save(); //修改订单信息
                if ( empty($orderSave) ) {
                    throw new \Exception('系统订单数据修改失败');
                }
                //修改问诊表状态
                $graphicSave = GraphicService::updateSave(['id'=>$order->diagnose_id,'status'=>1]);
                if ( empty($graphicSave) ) {
                    throw new \Exception('问诊数据状态修改失败');
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                Log::info('订单号:'.$message['out_trade_no'].'==>'.$e->getMessage());
                return $fail($e->getMessage());
            }
            //添加账单信息
            $billInsertArr = [
                'user_id'   => $order->user_id,
                'bill_no'   => getOrder(),
                'trade_no'  => $message['out_trade_no'],
                'source'    => 2,           //1商城 2图文咨询 3视频咨询
                'type'      => 1,           //1金额支付 2金币支付
                'amount'    => $order->amount,
            ];
            $billInsert = BillService::add($billInsertArr);
            if ( empty($billInsert) ) {
                Log::info('订单号:'.$message['out_trade_no'].'==>'.'账单数据添加失败');
            }
            return true; // 返回处理完成
        });

        $response->send(); // return $response;

    }

    public function cameraDiagnoseWechatCallBack(Request $request)  {
        Log::useDailyFiles(storage_path('logs/diagnose_pay/camera.log'));
        //\Log::info($request->all());
        $app = OrderService::getWechatPayInstance()->getInstance();
        $response = $app->handlePaidNotify(function($message, $fail){
            $messageJson = json_encode($message);
            Log::info($messageJson);
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order =OrderDiagnoseService::findByTradeNo($message['out_trade_no']);
            $order->notify_data = $messageJson;
            if (!$order || $order->status == self::ORDER_STATUS_PAID) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->pay_end_at = date('Y-m-d H:i:s',time()); // 更新支付时间为当前时间
                    $order->status = self::ORDER_STATUS_PAID;
                    $order->transaction_id = $message['transaction_id'];

                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = self::ORDER_STATUS_FAILED;
                }else{
                    Log::info('订单号:'.$message['out_trade_no'].'==>'.'订单状态错误');
                    return $fail('订单状态错误');
                }
            } else {
                Log::info('订单号:'.$message['out_trade_no'].'==>'.'通信失败，请稍后再通知我');
                return $fail('通信失败，请稍后再通知我');
            }

            $orderSave = $order->save(); // 保存订单
            if ( empty($orderSave) ) {
                Log::info('订单号:'.$message['out_trade_no'].'==>'.'系统订单数据修改失败');
                return $fail('系统订单数据修改失败');
            }
            //添加账单信息
            $billInsertArr = [
                'user_id'   => $order->user_id,
                'bill_no'   => getOrder(),
                'trade_no'  => $message['out_trade_no'],
                'source'    => 3,           //1商城 2图文咨询 3视频咨询
                'type'      => 1,           //1金额支付 2金币支付
                'amount'    => $order->amount,
            ];
            $billInsert = BillService::add($billInsertArr);
            if ( empty($billInsert) ) {
                Log::info('订单号:'.$message['out_trade_no'].'==>'.'账单数据添加失败');
            }
            return true; // 返回处理完成
        });

        $response->send(); // return $response;
    }


    /**
     * 图文咨询支付宝回调
     */
    public function alipayCallback(Request $request){
        Log::useDailyFiles(storage_path('logs/diagnose_pay/alipay.log'));
        $req = $request->all();
        /*\Log::info('alipay_res');
        \Log::info($req);*/
        Log::info(file_get_contents('php://input'));
        $order = OrderDiagnoseService::findByTradeNo($req['out_trade_no']);

        if (!$order || $order->status == self::ORDER_STATUS_PAID) { // 如果订单不存在 或者 订单已经支付过了
            echo 'success'; die;// 告诉支付宝，我已经处理完了，订单没找到，别再通知我了
        }
        if(array_key_exists('trade_status',$req) && 'TRADE_SUCCESS'==$req['trade_status']) {
            $order->pay_end_at = date('Y-m-d H:i:s',time()); // 更新支付时间为当前时间
            $order->status = self::ORDER_STATUS_PAID;
            $order->transaction_id = $req['trade_no'];
            $order->notify_data = json_encode($req);
            DB::beginTransaction();
            try{
                $orderSave = $order->save();
                if ( empty($orderSave) ) {
                    throw new \Exception('系统订单数据修改失败');
                }
                //修改问诊表状态
                $graphicSave = GraphicService::updateSave(['id'=>$order->diagnose_id,'status'=>1]);
                if ( empty($graphicSave) ) {
                    throw new \Exception('问诊数据状态修改失败');
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                Log::info('订单号:'.$req['out_trade_no'].'==>'.$e->getMessage());
            }
            //添加账单信息
            $billInsertArr = [
                'user_id'   => $order->user_id,
                'bill_no'   => getOrder(),
                'trade_no'  => $req['out_trade_no'],
                'source'    => 2,           //1商城 2图文咨询 3视频咨询
                'type'      => 1,           //1金额支付 2金币支付
                'amount'    => $order->amount,
            ];
            $billInsert = BillService::add($billInsertArr);
            if ( empty($billInsert) ) {
                Log::info('订单号:'.$req['out_trade_no'].'==>'.'账单数据添加失败');
            }
            echo 'success'; //告诉支付宝后台，处理完成
        }else{
            Log::error('订单号:'.$req['out_trade_no'].'paid error:'.json_encode($req));
        }
    }
}